#include "animationtext.h"

#include <QTimer>

AnimationText::AnimationText(QComboBox *parent)
    : QLabel(parent)
    , m_parent(parent)
{
    setGeometry(parent->geometry());
    move(x()+20, y());
    setStyleSheet("color: #a0a0a0");

    auto animation = new QTimer(this);
    animation->setInterval(100);
    connect(animation, &QTimer::timeout, [&](){
        if (m_parent->currentText().isEmpty()) {
            if (isHidden()) show();
            showAnimationText();
        } else {
            hide();
        }
    });
    
    QTimer::singleShot(500, [=](){
        resize(parent->size() + QSize(-20, 0));
        animation->start();
    });
}

QStringList AnimationText::textList() const
{
    return m_textList;
}

void AnimationText::setTextList(const QStringList &newTextList)
{
    if (m_textList == newTextList)
        return;
    m_textList = generateAnimationTextList(newTextList);
    emit textListChanged();
}

QStringList AnimationText::generateAnimationTextList(QStringList newTextList)
{
    QStringList animationTextList;
    foreach (auto text, newTextList) {
        animationTextList << "";

        int length = text.size();
        for (int i = 0; i < length; ++i) {
            animationTextList << text.left(i);
        }

        for (int i = 0; i < 4; ++i) {
            animationTextList << text;
        }

        for (int i = length; i >0 ; --i) {
            animationTextList << text.left(i);
        }

        animationTextList << ">";
    }

    return animationTextList;
}

void AnimationText::showAnimationText()
{
    if (m_currentIndex >= m_textList.size()) {
        m_currentIndex = 0;
    }

    if ((m_currentIndex+1) <= m_textList.size()) {
        setText(m_textList[m_currentIndex++]);
    }
}

int AnimationText::currentIndex() const
{
    return m_currentIndex;
}

void AnimationText::setCurrentIndex(int newCurrentIndex)
{
    if (m_currentIndex == newCurrentIndex)
        return;
    m_currentIndex = newCurrentIndex;
    emit currentIndexChanged();
}
